package com.example.coreshopapp.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.coreshopapp.R;
import com.example.coreshopapp.bean.GoodsCategoryData;

import java.util.ArrayList;
import java.util.List;

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
    private List<GoodsCategoryData> categoryData = new ArrayList<>();
    private int currentIndex = 0; // 选中当前分类

    public CategoryAdapter(List<GoodsCategoryData> categoryData) {
        this.categoryData = categoryData;
    }
    public void updateGoodsCategory(List<GoodsCategoryData> categoryData) {
        this.categoryData = categoryData;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public CategoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(parent.getContext(), R.layout.item_classify, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CategoryAdapter.ViewHolder holder, int position) {
        GoodsCategoryData item = categoryData.get(position);
        holder.tv_name.setText(item.getName());
        // 元素点击事件
        holder.tv_name.setOnClickListener(view -> {
            if(onItemClickListener != null) {
                onItemClickListener.onItemClick(position);
            }
        });
        // 判断是否选中index和点击index是一致，一致就高亮
        if(currentIndex == position) {
            holder.tv_name.setBackgroundResource(R.drawable.type_selector_bg);
        } else {
            holder.tv_name.setBackgroundResource(R.drawable.type_uncheck_bg);
        }
    }

    @Override
    public int getItemCount() {
        return categoryData.size();
    }
    public class ViewHolder extends  RecyclerView.ViewHolder {
    private TextView tv_name;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_name = itemView.findViewById(R.id.tv_name);
        }
    }
    // 1.定义自定义点击事件
    public interface OnItemClickListener {
        void onItemClick(int position);
    }
    //    2.初始化点击时间
    public OnItemClickListener onItemClickListener;
    // 3. 定义构造函数方法，在主页面onCreate点击出发时传递回来，在再点击事件判断是否调用，有调用，把当前索引传递
    public void setOnItemClickListener(OnItemClickListener onMyItemClickListener) {
        onItemClickListener = onMyItemClickListener;
    }

    //  在oncreate拿到点击的索引传递回来
    public  void setCurrentIndex(int i) {
        currentIndex = i;
        // 刷新不能少一定要写
        notifyDataSetChanged();
    }
}
